
/**
 * Module dependencies.
 */

var http = require('http')
  , fs = require('fs')
  , path = require('path');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Load configurations
var env = process.env.NODE_ENV || 'development'
  , config = require('./config/config')[env]
  , mongoose = require('mongoose')

// Connect to mongodb
var connect = function () {
  var options = { server: { socketOptions: { keepAlive: 1 } } }
  mongoose.connect(config.db, options)
}
connect()

// Error handler
mongoose.connection.on('error', function (err) {
  console.log(err)
})

// Reconnect when closed
mongoose.connection.on('disconnected', function () {
  //connect()
})

// Bootstrap models
var models_path = __dirname + '/app/models'
fs.readdirSync(models_path).forEach(function (file) {
  if (~file.indexOf('.js')) require(models_path + '/' + file)
})


var app = require('express')();
require('./config/express')(app, config);
require('./config/routes')(app, config);
require('./tools/extension');

var port = process.env.PORT || 3000
app.listen(port)

console.log('Express app started on port '+port)